<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统连接诊断</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        .status-success { background-color: #10b981; }
        .status-error { background-color: #ef4444; }
        .status-testing { background-color: #3b82f6; }
    </style>
</head>
<body class="bg-gray-100 p-8">
    <div class="max-w-4xl mx-auto">
        <h1 class="text-2xl font-bold mb-6">🔍 EndoSight-UC 系统连接诊断</h1>

        <div class="bg-white rounded-lg shadow p-6 mb-4">
            <h2 class="text-lg font-semibold mb-4">基础连接测试</h2>
            <div id="results" class="space-y-2"></div>
        </div>

        <div class="bg-white rounded-lg shadow p-6">
            <h2 class="text-lg font-semibold mb-4">诊断日志</h2>
            <div id="logs" class="bg-gray-900 text-green-400 p-4 rounded font-mono text-sm h-64 overflow-y-auto"></div>
        </div>
    </div>

    <script>
        function addLog(message, type = 'info') {
            const logs = document.getElementById('logs');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');

            let colorClass = 'text-gray-400';
            let icon = '📝';

            switch(type) {
                case 'success': colorClass = 'text-green-400'; icon = '✅'; break;
                case 'error': colorClass = 'text-red-400'; icon = '❌'; break;
                case 'warning': colorClass = 'text-yellow-400'; icon = '⚠️'; break;
                case 'info': colorClass = 'text-blue-400'; icon = 'ℹ️'; break;
            }

            logEntry.className = colorClass;
            logEntry.innerHTML = `<span class="text-gray-500">[${timestamp}]</span> ${icon} ${message}`;
            logs.appendChild(logEntry);
            logs.scrollTop = logs.scrollHeight;
        }

        function addResult(service, status, details) {
            const results = document.getElementById('results');
            const result = document.createElement('div');
            result.className = 'flex items-center justify-between p-2 bg-gray-50 rounded';

            let statusClass = 'status-testing';
            let statusText = '测试中';

            if (status === 'success') {
                statusClass = 'status-success';
                statusText = '✅ 正常';
            } else if (status === 'error') {
                statusClass = 'status-error';
                statusText = '❌ 失败';
            }

            result.innerHTML = `
                <span class="flex items-center">
                    <span class="status-indicator ${statusClass}"></span>
                    ${service}
                </span>
                <span class="text-sm text-gray-600">${details}</span>
            `;

            results.appendChild(result);
        }

        async function testConnection() {
            addLog('开始系统连接诊断...', 'info');

            // 测试后端API
            addResult('后端API (4000)', 'testing', '测试中...');
            try {
                const response = await fetch('http://localhost:4000/api/health', {
                    mode: 'cors'
                });
                if (response.ok) {
                    const data = await response.json();
                    addResult('后端API (4000)', 'success', data.message);
                    addLog('后端API连接成功', 'success');
                } else {
                    addResult('后端API (4000)', 'error', `HTTP ${response.status}`);
                    addLog(`后端API响应异常: ${response.status}`, 'error');
                }
            } catch (error) {
                addResult('后端API (4000)', 'error', error.message);
                addLog(`后端API连接失败: ${error.message}`, 'error');

                // 尝试使用XMLHttpRequest作为备选方案
                addLog('尝试使用XMLHttpRequest连接后端...', 'warning');
                try {
                    await testBackendWithXHR();
                } catch (xhrError) {
                    addLog(`XMLHttpRequest也失败: ${xhrError.message}`, 'error');
                }
            }

            // 测试AI服务
            addResult('AI服务 (5001)', 'testing', '测试中...');
            try {
                const response = await fetch('http://localhost:5001/health', {
                    mode: 'cors'
                });
                if (response.ok) {
                    const data = await response.json();
                    addResult('AI服务 (5001)', 'success', `状态: ${data.status}`);
                    addLog('AI服务连接成功', 'success');
                } else {
                    addResult('AI服务 (5001)', 'error', `HTTP ${response.status}`);
                    addLog(`AI服务响应异常: ${response.status}`, 'error');
                }
            } catch (error) {
                addResult('AI服务 (5001)', 'error', error.message);
                addLog(`AI服务连接失败: ${error.message}`, 'error');
            }

            // 测试前端应用
            addResult('前端应用 (8101)', 'testing', '测试中...');
            try {
                const response = await fetch('http://localhost:8101/', {
                    mode: 'cors'
                });
                if (response.ok) {
                    addResult('前端应用 (8101)', 'success', 'Vue应用运行正常');
                    addLog('前端应用连接成功', 'success');
                } else {
                    addResult('前端应用 (8101)', 'error', `HTTP ${response.status}`);
                    addLog(`前端应用响应异常: ${response.status}`, 'error');
                }
            } catch (error) {
                addResult('前端应用 (8101)', 'error', error.message);
                addLog(`前端应用连接失败: ${error.message}`, 'error');
            }

            addLog('诊断完成', 'info');
        }

        // 使用XMLHttpRequest测试后端
        function testBackendWithXHR() {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            try {
                                const data = JSON.parse(xhr.responseText);
                                addResult('后端API (4000) - XHR', 'success', data.message);
                                addLog('XMLHttpRequest连接后端成功', 'success');
                                resolve();
                            } catch (e) {
                                addResult('后端API (4000) - XHR', 'success', '响应正常');
                                addLog('XMLHttpRequest连接成功', 'success');
                                resolve();
                            }
                        } else {
                            addResult('后端API (4000) - XHR', 'error', `HTTP ${xhr.status}`);
                            addLog(`XMLHttpRequest失败: ${xhr.status}`, 'error');
                            reject(new Error(`HTTP ${xhr.status}`));
                        }
                    }
                };
                xhr.onerror = function() {
                    addResult('后端API (4000) - XHR', 'error', '网络错误');
                    addLog('XMLHttpRequest网络错误', 'error');
                    reject(new Error('网络错误'));
                };
                xhr.open('GET', 'http://localhost:4000/api/health', true);
                xhr.send();
            });
        }

        // 页面加载后自动运行测试
        window.addEventListener('load', () => {
            setTimeout(testConnection, 1000);
        });
    </script>
</body>
</html>